package com.qk.management.web.interceptor;


import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
@SuppressWarnings("all")
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final String TOKEN_HERDER_NAME  = "token";
    /**
     * 拦截请求，在到达控制器之前执行
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return true:放行，false:拦截
     * @throws Exception 抛出异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("-----------------拦截器执行了-----------------");

        //1、获取请求头中的token
        String token = request.getHeader(TOKEN_HERDER_NAME);
        //2、判断token是否为空 java8 判空 Optional.ofNullable(token).isPresent()
        if (Objects.isNull(token)){
            log.info("请求头中没有token");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try{
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("token验证成功");
            log.info("当前用户是：{}", username);
            Integer id = claims.get("id",Integer.class);
            CurrentUserContextHolders.set(id);
            log.info("当前用户id是：{}", id);
            return true;
        }catch (Exception e){
            log.error("token验证失败：{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }

    //移除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
